package com.nayun.gjh.xiaokabanghou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nayun.gjh.xiaokabanghou.common.*;
import com.nayun.gjh.xiaokabanghou.mapper.UserMapper;
import com.nayun.gjh.xiaokabanghou.model.Diuzhao;
import com.nayun.gjh.xiaokabanghou.model.User;
import com.nayun.gjh.xiaokabanghou.model.request.SafetyUserRequest;
import com.nayun.gjh.xiaokabanghou.model.response.SafetyDiuShiRecordResponse;
import com.nayun.gjh.xiaokabanghou.model.response.SafetyFinderUserResponse;
import com.nayun.gjh.xiaokabanghou.model.response.SafetyLoseUserResponse;
import com.nayun.gjh.xiaokabanghou.model.response.SafetyUserResponse;
import com.nayun.gjh.xiaokabanghou.service.DiuzhaoService;
import com.nayun.gjh.xiaokabanghou.mapper.DiuzhaoMapper;
import com.nayun.gjh.xiaokabanghou.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

import static com.nayun.gjh.xiaokabanghou.common.CustomMailSender.MailSendToLoser;

/**
 * @author tsin0
 * @description 针对表【diuzhao】的数据库操作Service实现
 * @createDate 2024-02-04 09:42:19
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DiuzhaoServiceImpl extends ServiceImpl<DiuzhaoMapper, Diuzhao>
        implements DiuzhaoService {

    @Resource
    private DiuzhaoMapper diuzhaoMapper;
    @Resource
    private UserMapper userMapper;
    public static final String SALT = "XiaoKabangBygjh2024";


    @Override
    public SafetyDiuShiRecordResponse uploadLoseRecord(String cordCode, int status, SafetyUserRequest loginUser) throws Exception {
        if (cordCode == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "卡号为空");
        }
        //纯数字
        boolean matches = Pattern.matches("\\d+", cordCode);
        if (!matches) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不是号码格式");
        }
        //6位
        if (cordCode.length() != 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "长度不是6位");
        }
        //查库
        QueryWrapper<Diuzhao> cardQueryWrapper = new QueryWrapper<>();
        //加密
        String safetyCordCode = new DesUtil(SALT).encrypt(cordCode, "CBC");
        /*
        * 卡状态
            10-拾卡者发布未找到失主
            11-失主发布未找到拾卡者
            20-拾卡者发布已找到失主
            21-失主发布已找到拾卡者
        * */
        cardQueryWrapper.eq("status", 10).or().eq("status", 11);

        List<Diuzhao> LoseFindCordList = diuzhaoMapper.selectList(cardQueryWrapper);
        ArrayList<Diuzhao> LoseFindCordListQ = new ArrayList<>();
        for (Diuzhao oDiuzhao : LoseFindCordList) {
            if (safetyCordCode.equals(oDiuzhao.getCardcodeLeastsix())) {
                LoseFindCordListQ.add(oDiuzhao);
            }
        }
        //不可重复
        if (LoseFindCordListQ.size() > 1) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
        }
        if (LoseFindCordListQ.isEmpty()) {
            //没有就新增
            Diuzhao diuzhao = new Diuzhao();
            diuzhao.setCardUid(String.valueOf(UUID.randomUUID()));
            diuzhao.setZhaoUid(loginUser.getUc());
            diuzhao.setCardcodeLeastsix(safetyCordCode);
            diuzhao.setStatus(status);
            diuzhao.setCreateTime(new Date());
            boolean save = this.save(diuzhao);
            if (!save) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "新增记录失败");
            }
            cardQueryWrapper.eq("cardcode_leastsix", safetyCordCode);
//            cardQueryWrapper.eq("status", 10).or().eq("status", 11);
            List<Diuzhao> LoseFindCordList2 = diuzhaoMapper.selectList(cardQueryWrapper);
            ArrayList<Diuzhao> LoseFindCordList3 = new ArrayList<>();
            for (Diuzhao oDiuzhao : LoseFindCordList2) {
                if (safetyCordCode.equals(oDiuzhao.getCardcodeLeastsix())) {
                    LoseFindCordList3.add(oDiuzhao);
                }
            }
            if (LoseFindCordList3.size() > 1) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
            }
            Diuzhao diuzhao2 = LoseFindCordList3.get(0);
            SafetyDiuShiRecordResponse safetyDiuShiRecordResponse = new SafetyDiuShiRecordResponse();
            safetyDiuShiRecordResponse.setUc(diuzhao2.getCardUid());
            safetyDiuShiRecordResponse.setCardcodeLeastsix(cordCode);
            return safetyDiuShiRecordResponse;
        }
        //有
        Diuzhao diuzhaoAA = LoseFindCordList.get(0);
        Diuzhao diuzhao = new Diuzhao();
        diuzhao.setId(diuzhaoAA.getId());
        diuzhao.setZhaoUid(loginUser.getUc());
        boolean save = this.updateById(diuzhao);
        if (!save) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新增记录失败");
        }
        Diuzhao diuzhao1 = LoseFindCordListQ.get(0);
        String diuUid = diuzhao1.getDiuUid();
        //查库
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("uid", diuUid);
        List<User> users = userMapper.selectList(userQueryWrapper);
        if (users.size() > 1) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
        }
        if (users.isEmpty()) {
            throw new BusinessException(ErrorCode.DATA_NULL, "空？");
        }
        User loserUser = users.get(0);
        String stuNumber = new DesUtil(SALT).decrypt(loserUser.getStuNumber(), "CBC");
        String cardcodeLeastsix = new DesUtil(SALT).decrypt(loserUser.getCardcodeLeastsix(), "CBC");
        if(stuNumber!=null&&!stuNumber.isEmpty()){
            String stuNumMail = "vm" + stuNumber + "@jzxy.edu.cn";
            MailSendToLoser(stuNumMail, new Date(), cardcodeLeastsix);
        }
        return null;

    }

    @Override
    public SafetyLoseUserResponse searchLoseFindRecord(String cordCode, SafetyUserRequest loginUser) throws Exception {
        if (cordCode == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "卡号为空");
        }
        //纯数字
        boolean matches = Pattern.matches("\\d+", cordCode);
        if (!matches) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不是号码格式");
        }
        //6位
        if (cordCode.length() != 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "长度不是6位");
        }
        //查库
        QueryWrapper<Diuzhao> cardQueryWrapper = new QueryWrapper<>();
        //加密
        String safetyCordCode = new DesUtil(SALT).encrypt(cordCode, "CBC");
        cardQueryWrapper.eq("cardcode_leastsix", safetyCordCode);
        /*
        * 卡状态
            10-拾卡者发布未找到失主
            11-失主发布未找到拾卡者
            20-拾卡者发布已找到失主
            21-失主发布已找到拾卡者
        * */
        cardQueryWrapper.eq("status", 11);
        List<Diuzhao> LoseFindCordList = diuzhaoMapper.selectList(cardQueryWrapper);
        if (LoseFindCordList.isEmpty()) {
            return null;
        }
        if (LoseFindCordList.size() > 1) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
        }
        Diuzhao diuzhao = LoseFindCordList.get(0);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("uid", diuzhao.getDiuUid());
        List<User> users = userMapper.selectList(userQueryWrapper);
        if (users.size() > 1) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
        }
        if (users.isEmpty()) {
            throw new BusinessException(ErrorCode.DATA_NULL, "查询数据为空");
        }
        User loseUser = users.get(0);
        //解密
        String phone = new DesUtil(SALT).decrypt(loseUser.getPhone(), "CBC");
        String cardcodeLeastsix = new DesUtil(SALT).decrypt(loseUser.getCardcodeLeastsix(), "CBC");
        SafetyLoseUserResponse safetyLoseUserResponse = new SafetyLoseUserResponse();
        if (loseUser.getUserName() == null) {
            safetyLoseUserResponse.setPhone(phone);
        } else {
            safetyLoseUserResponse.setUserName(loseUser.getUserName());
        }
        safetyLoseUserResponse.setCardcodeLeastsix(cardcodeLeastsix);
        safetyLoseUserResponse.setCardStatus(loseUser.getCardStatus());
        return safetyLoseUserResponse;
    }

    @Override
    public SafetyFinderUserResponse searchFinder(SafetyUserRequest loginUser) throws Exception {
        String uc = loginUser.getUc();
        //查库
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("uid", uc);
        List<User> userList = userMapper.selectList(userQueryWrapper);
        if (userList.isEmpty()) {
            return null;
        }
        if (userList.size() > 1) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
        }
        User loseUser = userList.get(0);

        QueryWrapper<Diuzhao> cardQueryWrapper = new QueryWrapper<>();
        cardQueryWrapper.eq("cardcode_leastsix", loseUser.getCardcodeLeastsix());
        cardQueryWrapper.eq("status", 11);
        List<Diuzhao> LoseFindCordList = diuzhaoMapper.selectList(cardQueryWrapper);
        if (LoseFindCordList.isEmpty()) {
            return null;
        }
        if (LoseFindCordList.size() > 1) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
        }
        Diuzhao diuzhao = LoseFindCordList.get(0);
        String zhaoUid = diuzhao.getZhaoUid();
        QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
        userQueryWrapper2.eq("uid", zhaoUid);
        List<User> userListZhao = userMapper.selectList(userQueryWrapper2);
        if (userListZhao.isEmpty()) {
            return null;
        }
        if (userListZhao.size() > 1) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
        }
        User findUser = userListZhao.get(0);
        //解密
        String phone = new DesUtil(SALT).decrypt(findUser.getPhone(), "CBC");
        SafetyFinderUserResponse safetyFinderUserResponse = new SafetyFinderUserResponse();
        if (findUser.getUserName() == null) {
            safetyFinderUserResponse.setPhone(phone);
        } else {
            safetyFinderUserResponse.setUserName(findUser.getUserName());
        }
        return safetyFinderUserResponse;
    }

    @Override
    public ArrayList<String> leastCardList() throws Exception {
        QueryWrapper<Diuzhao> cardQueryWrapper = new QueryWrapper<>();
          /*
        * 卡状态
            10-拾卡者发布未找到失主
            11-失主发布未找到拾卡者
            20-拾卡者发布已找到失主
            21-失主发布已找到拾卡者
        * */
        cardQueryWrapper.eq("status", 10).or().eq("status", 11);
        List<Diuzhao> LoseFindCordList = diuzhaoMapper.selectList(cardQueryWrapper);
        ArrayList<String> safetyDiuShiRecordResponses = new ArrayList<>();
        for (Diuzhao diuzhao : LoseFindCordList) {
            if (diuzhao.getStatus().equals(10)) {
                String cardcodeLeastsix = new DesUtil(SALT).decrypt(diuzhao.getCardcodeLeastsix(), "CBC");
                safetyDiuShiRecordResponses.add("有同学捡到尾号[" + cardcodeLeastsix + "]的卡");
            } else if (diuzhao.getStatus().equals(11)) {
                String cardcodeLeastsix = new DesUtil(SALT).decrypt(diuzhao.getCardcodeLeastsix(), "CBC");
                safetyDiuShiRecordResponses.add("丢失一张尾号[" + cardcodeLeastsix + "]的卡，求帮助");
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
            }
        }
        return safetyDiuShiRecordResponses;
    }


}




